package com.bml.architect.alibaba.web;

import com.bml.architect.alibaba.service.AccountServiceProvider;
import com.bml.architect.alibaba.service.OrderService;
import com.bml.architect.alibaba.vo.OrderInfo;
import com.bml.architect.alibaba.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/channel")
public class ChannelController {



    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AccountServiceProvider accountServiceProvider;


    @RequestMapping("/account/{usreId}")
    public R queryAccount(@PathVariable("usreId") Integer usreId){

        return accountServiceProvider.findUserById(usreId);
    }


    @RequestMapping("/get/{usreId}")
    public String queryAccount(@PathVariable("usreId") String usreId){

        return "userid is "+ usreId;
    }








    @RequestMapping("/getOrder")
    @ResponseBody
    public OrderInfo getOrder(){
        String url = "http://alibaba-order/order/get";
        //String url = "http://" + getUri("alibaba-order")+"/order/get";
        return restTemplate.getForObject(url, OrderInfo.class);

       // return orderService.getOrder();
    }

    @Autowired
    private DiscoveryClient discoveryClient;
    public String getUri(String serviceName) {
        // 获取服务的实例
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
        if (serviceInstances == null || serviceInstances.isEmpty()) {
            return null;
        }
        int serviceSize = serviceInstances.size();
        //轮询
        int indexServer = incrementAndGetModulo(serviceSize);
        return serviceInstances.get(indexServer).getUri().toString();
    }
    private AtomicInteger nextIndex = new AtomicInteger(0);
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextIndex.get();
            int next = (current + 1) % modulo;
            if (nextIndex.compareAndSet(current, next) && current < modulo){
                return current;
            }
        }
    }
}
